import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';
import _ from 'lodash';
import qs from 'qs';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  DatePicker,
  Button,
  Descriptions,
  Table,
  message,
  Tooltip,
} from 'antd';

import { TableListData } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Descriptions;

const time = new Date().getTime();
const lastWeek = time - 1000 * 60 * 60 * 24 * 7;

const { pathname } = window.location;

interface MouthDetailProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: TableListData;
  statusList: any[];
  location: { query: any };
  INITINFO: any;
}

interface MouthDetailState {
  rowId:number;
  searchValues: any;
}

@connect(({
  historyOrderList: { dataInfo, statusList },
  common: { INITINFO },
  loading,
}: any) => ({
  dataInfo,
  statusList,
  INITINFO,
  loading: loading.effects['historyOrderList/fetch'],
}))

class MouthDetailElem extends Component<MouthDetailProps, MouthDetailState> {
  columns = [
    {
      title: '　运单号',
      dataIndex: 'expCode',
      width: 120,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit" style={{ maxWidth: 120 }}>{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '开箱密码',
      dataIndex: 'openCode',
      width: 100,
    },
    {
      title: '收件人手机',
      dataIndex: 'consigneePhone',
      width: 120,
    },
    {
      title: '投递人手机',
      dataIndex: 'courierPhone',
      width: 120,
    },
    {
      title: '入库时间',
      dataIndex: 'inTime',
      width: 150,
    },
    {
      title: '出库时间',
      dataIndex: 'outTime',
      render: (text: string) => text || '--',
      width: 150,
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
    },
    {
      title: '批次号',
      dataIndex: 'batchName',
      width: 80,
      render: (text: string) => text || '--',
    },
    {
      title: '投递类型',
      dataIndex: 'deliveryWayName',
      width: 120,
    },
    {
      title: '订单状态',
      dataIndex: 'statusName',
      width: 100,
    },
    {
      title: '短信状态',
      dataIndex: 'smsStatus',
      width: 100,
    },
  ];

  state: MouthDetailState = {
    rowId: 0,
    searchValues: {},
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    if (query && query.cellId) {
      return {
        searchValues: {
          ...values,
          storageId: query.cellId,
          pageIndex: Number(pageIndex) || 1,
          pageSize: Number(pageSize) || 20,
        },
      };
    }
    return null;
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
    this.fetchAction('fetchStatus');
    this.fetchAction('common/fetchExpressList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    const {
      location: { query: { cellId } },
    } = this.props;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || cellId !== prevProps.location.query.cellId
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const {
      searchValues: {
        pageIndex,
        pageSize,
        cabinetName,
        cabinetCode,
        cellCode,
        cellId,
        cellType,
        storageId,
        storageType,
        ...values
      },
    } = this.state;
    const params = this.turnValuesType(values);

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => {
    const format = 'YYYY-MM-DD HH:mm:ss';
    const { startTime, endTime, ...params } = values;
    const start = startTime ? moment(startTime, format) : moment().subtract(7, 'days');
    const end = endTime && moment(endTime, format);

    return {
      // 转换数据类型
      ...params,
      startAndEndDate: [start, end],
      batchDate: values.batchDate && moment(values.batchDate, format),
      status: values.status || '0',
    };
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    const { startTime } = searchValues;
    const params = {
      ...searchValues,
      startTime: startTime || moment(moment().subtract(7, 'days')).format('YYYY-MM-DD HH:mm:ss'),
      storageType: 1,
    };

    delete params.cabinetCode;
    delete params.cabinetName;
    delete params.cellCode;
    delete params.cellId;
    delete params.cellType;

    return params;
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const {

      form: { validateFields },
      location: { query },
    } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { startAndEndDate, batchDate, ...remain } = values;
      if (values.seqNo && !batchDate) {
        message.error('请选择批次日期');
        return;
      }
      if (batchDate && !values.seqNo) {
        message.error('请输入批次编号');
        return;
      }

      const format = 'YYYY-MM-DD HH:mm:ss';
      const startTime = startAndEndDate[0]
        ? moment(startAndEndDate[0]).format(format)
        : moment().subtract(7, 'days');

      const endTime = moment(startAndEndDate[1] || new Date()).format(format);

      const params = {
        ...query,
        ...remain,
        startTime,
        endTime,
        batchDate: batchDate && `${moment(batchDate).format(format)}`,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `格口${query.cellCode}订单`,
        url: `${pathname}?${qs.stringify(params)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const {
      location: {
        query: {
          startAndEndDate,
          cabinetName,
          cabinetCode,
          cellId,
          cellCode,
          cellType,
        },
      },
    } = this.props;

    const start = moment(
      startAndEndDate && typeof startAndEndDate === 'object'
        ? startAndEndDate[0] : new Date(lastWeek),
      'YYYY-MM-DD HH:mm:ss',
    );
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ startAndEndDate: [start], status: 0 });

    const params = {
      cabinetName,
      cabinetCode,
      cellId,
      cellCode,
      cellType,
    };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `格口${cellCode}订单`,
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const { location: { query } } = this.props;
    const params = {
      ...searchValues,
      ...query,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `格口${query.cellCode}订单`,
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `historyOrderList/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      searchValues: { pageIndex, pageSize },
    } = this.state;
    const {
      dataInfo,
      statusList,
      form: { getFieldDecorator },
      location: { query },
      INITINFO: { expressList },
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Descriptions column={4} style={{ lineHeight: '32px' }}>
                <Item label="柜体名称" className="marginB12">{query.cabinetName}</Item>
                <Item label="柜体编号" className="marginB12">{query.cabinetCode}</Item>
                <Item label="格口编号" className="marginB12">{query.cellCode}</Item>
                <Item label="格口类型">{query.cellType}</Item>
              </Descriptions>
            </Row>
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Form.Item label="起止时间" colon={false}>
                  {getFieldDecorator('startAndEndDate')(
                    <RangePicker
                      showTime
                      placeholder={['开始时间', '截止时间']}
                      style={{ width: '100%' }}
                      disabledDate={timeLimit}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                          moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                        ],
                      }}
                    />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="收件手机" colon={false}>
                  {getFieldDecorator('consigneePhone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="　运单号" colon={false}>
                  {getFieldDecorator('expCode')(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="投递手机" colon={false}>
                  {getFieldDecorator('courierPhone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="快递公司" colon={false}>
                  {getFieldDecorator('expressId')(
                    <Select allowClear placeholder="请选择">
                      {expressList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="批次日期" colon={false}>
                  {getFieldDecorator('batchDate')(
                    <DatePicker placeholder="请选择日期" style={{ width: '100%' }} />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="订单状态" colon={false}>
                  {getFieldDecorator('status')(
                    <Select allowClear placeholder="请选择">
                      {statusList.map((item: any) => (
                        <Option value={String(item.value)} key={item.value}>
                          {item.label}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="批次编号" colon={false}>
                  {getFieldDecorator('seqNo')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={18}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<MouthDetailProps>()(MouthDetailElem);
